package Java7_Concurrency_Cookbook.concurrent_custom.custom_fork_join_worker_thread;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.RecursiveTask;

/**
 * @author lixiangke
 * @date 2017/11/27
 */
public class MyRecursiveTask extends RecursiveTask<Integer> {
    private int[] array;
    private int start, end;

    public MyRecursiveTask(int[] array, int start, int end) {
        this.array = array;
        this.start = start;
        this.end = end;
    }

    List<MyRecursiveTask> myRecursiveTasks = new ArrayList<>();

    @Override
    protected Integer compute() {
        Integer ret = 0;
        MyWorkerThread thread = (MyWorkerThread)Thread.currentThread();
        if (end - start > 100) {
            int mid = (end + start) / 2;
            MyRecursiveTask task1 = new MyRecursiveTask(array, start, mid);
            MyRecursiveTask task2 = new MyRecursiveTask(array, mid, end);
            invokeAll(task1, task2);
            // ret = addResults(task1, task2);
            // System.out.println("Return: " + ret);
        } else {
            thread.addTask();
        }
        return ret;
    }

    private Integer addResults(MyRecursiveTask task1, MyRecursiveTask task2) {
        int value;
        try {
            value = task1.get().intValue() + task2.get().intValue();
            System.out.println(value);
        } catch (InterruptedException e) {
            e.printStackTrace();
            value = 0;
        } catch (ExecutionException e) {
            e.printStackTrace();
            value = 0;
        }
        return value;
    }
}
